package edu.towson.cis.cosc490.jirani.apple.main;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import edu.towson.cis.cosc490.jirani.apple.R;
import edu.towson.cis.cosc490.jirani.apple.SavedActivity;
import edu.towson.cis.cosc490.jirani.apple.data.Constants;
import edu.towson.cis.cosc490.jirani.apple.data.AppleData;
import edu.towson.cis.cosc490.jirani.apple.data.SavedConstants;
import edu.towson.cis.cosc490.jirani.apple.data.SavedData;
import edu.towson.cis.cosc490.jirani.apple.parsers.AndroidSaxFeedParser;

public class AppleMainActivity extends ListActivity {
	
	private List<AppleItem> apples;
	private AppleData appledata;
	private SavedData saveddata;
	private boolean serviceFlag;
	AlarmManager alarms;
	private String feedURL = "https://www.apple.com/main/rss/hotnews/hotnews.rss";
	int pos = 0;
	MediaPlayer player;
	
    
	@Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.main);
        appledata = new AppleData(this);
        saveddata = new SavedData(this);
        loadFeed();
        setAlarm();
        registerForContextMenu(getListView());
        player = MediaPlayer.create(this, R.raw.apples);
        player.start();
    } 
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		pos = position;
		Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(apples.get(position).getLink().toExternalForm()));
		startActivity(viewMessage);
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater(); 
		inflater.inflate(R.menu.options_menu, menu); 
		return true;
	}
 
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) 
		{
		case R.id.Refresh:
			loadFeed();
		break;
		case R.id.Start: 
	          if(!serviceFlag) setAlarm();
	    break;
		case R.id.Stop: 
	          if(serviceFlag) cancelAlarm();
	    break;
		} 
		return true;
	}
	
	private void setAlarm(){
		serviceFlag = true;
	    Intent downloader = new Intent(this, AlarmReceiver.class);
	    PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
	    
	    alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
	    alarms.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 60000, recurringDownload);
	    System.out.println("Setting alarm...");
	}
	
	private void cancelAlarm(){
		serviceFlag = false;
		Intent downloader = new Intent(this, AlarmReceiver.class);
	    PendingIntent recurringDownload = PendingIntent.getBroadcast(this, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
		
	    alarms.cancel(recurringDownload);
	}
	
	private void loadFeed(){
    	try{
    	
	    	AndroidSaxFeedParser parser = new AndroidSaxFeedParser(feedURL);
	       	apples = parser.parse();
	    	
	    	List<String> titles = new ArrayList<String>(apples.size());
	    	
	    	for (AppleItem ad : apples){
	    		titles.add(ad.getTitle());
	    		
	    		try{
	    			addFarkItem(ad.getDescription(), "" + ad.getTitle(), ad.getLink().toString(), ad.getDate());
	    		}
	    		catch(Exception e){e.printStackTrace();}
	    	}
	    	
	    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.reddit_item,titles);
	    	this.setListAdapter(adapter);
    	} catch (Throwable t){}
    }
		
	private void addFarkItem(String des,String title,String link,String pubDate){
        SQLiteDatabase db = appledata.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Constants.DES, des);
        values.put(Constants.TITLE, title);
        values.put(Constants.LINK, link);
        values.put(Constants.PUBDATE, pubDate);
        db.insertOrThrow(Constants.TABLE_NAME, null, values);
     }	
	
	private void addSavedItem(String des,String title,String link,String pubDate){
        SQLiteDatabase db = saveddata.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Constants.DES, des);
        values.put(Constants.TITLE, title);
        values.put(Constants.LINK, link);
        values.put(Constants.PUBDATE, pubDate);
        db.insertOrThrow(Constants.TABLE_NAME, null, values);
     }	
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
 		super.onCreateContextMenu(menu, v, menuInfo);
 		MenuInflater inflater = getMenuInflater();
 		inflater.inflate(R.menu.context_menu, menu);
 	}
 	
 	public boolean onContextItemSelected(MenuItem item){
 		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
 		switch(item.getItemId()){
 		case R.id.item1:
 			Intent smsIntent = new Intent(Intent.ACTION_VIEW);
 			smsIntent.putExtra("sms_body", apples.get((int)info.id).getTitle() + "  " + apples.get((int)info.id).getLink());
 			smsIntent.putExtra("address", "4103334444");
 			smsIntent.setType("vnd.android-dir/mms-sms");
 			startActivity(smsIntent);
 			return true;
 		case R.id.item2:
 			Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
 			
 			emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "cosc490spring2014@gmail.com");
 			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Check out this Article!");
 			emailIntent.putExtra(Intent.EXTRA_TEXT, apples.get((int)info.id).getTitle() + "  " + apples.get((int)info.id).getLink());
 			emailIntent.setType("plain/text");
 			startActivity(emailIntent);
 			return true;
 		case R.id.item3:
 			String tweetUrl = "https://twitter.com/intent/tweet?text="
                    + apples.get((int)info.id).getTitle() + "&url=" + apples.get((int)info.id).getLink();
 			Uri uri = Uri.parse(tweetUrl);
 			startActivity(new Intent(Intent.ACTION_VIEW, uri));	
 			return true;
 		case R.id.item4:
 			Intent shareIntent = new Intent(Intent.ACTION_SEND);
 			  shareIntent.setType("text/plain");
 			  shareIntent.putExtra(Intent.EXTRA_TEXT, apples.get((int)info.id).getTitle() + "  " + apples.get((int)info.id).getLink());
 			  startActivity(Intent.createChooser(shareIntent, "Share..."));
 			return true;
 		case R.id.item5:
 			Intent i = new Intent(AppleMainActivity.this, SavedActivity.class);
 			List<String> titles = new ArrayList<String>(1);
 			titles.add(apples.get((int)info.id).getTitle());
 			addSavedItem(apples.get((int)info.id).getDescription(), apples.get((int)info.id).getTitle(), apples.get((int)info.id).getTitle().toString(), apples.get((int)info.id).getDate());
 			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_saved,titles);
	    	this.setListAdapter(adapter);
 			startActivityForResult(i, 2);
 			return true;
 		default:
 			return super.onContextItemSelected(item);
 			
 		}
 	}
 	
 	public void onDestroy() {
 	    super.onDestroy();
 	    player.stop();
 	}
	
}